package com.fr.web.core.service;

import com.fr.base.CodeUtils;
import com.fr.base.ColumnRow;
import com.fr.base.FRContext;
import com.fr.base.StringUtils;
import com.fr.base.core.BaseCoreUtils;
import com.fr.base.core.ComparatorUtils;
import com.fr.base.core.FRCoreContext;
import com.fr.base.core.RSADecode;
import com.fr.base.core.html.Html;
import com.fr.base.core.html.Tag;
import com.fr.base.core.json.JSONArray;
import com.fr.base.core.json.JSONException;
import com.fr.base.core.json.JSONObject;
import com.fr.base.core.util.TemplateUtils;
import com.fr.base.core.util.vt.VT4FR;
import com.fr.base.core.util.vt.VT4FR.FUNC;
import com.fr.base.file.ConfigManager;
import com.fr.report.CellElement;
import com.fr.report.EditResultWorkSheet.EditCellELement;
import com.fr.report.FloatElement;
import com.fr.report.RWorkBook;
import com.fr.report.Report;
import com.fr.report.ReportPageAttr;
import com.fr.report.ReportSettings;
import com.fr.report.ResultReport;
import com.fr.report.ResultWorkBook;
import com.fr.report.core.DynamicValueList;
import com.fr.report.core.ReportHelper;
import com.fr.report.core.ReportUtils;
import com.fr.report.io.DefaultResultSaver;
import com.fr.report.io.ResultSaver;
import com.fr.report.io.TemplateImporter;
import com.fr.report.js.NameJavaScriptGroup;
import com.fr.report.script.Calculator;
import com.fr.util.Consts;
import com.fr.web.Browser;
import com.fr.web.ErrorHandler;
import com.fr.web.Repository;
import com.fr.web.core.ErrorHandlerHelper;
import com.fr.web.core.HTMLWriter;
import com.fr.web.core.HTMLWriterUtils;
import com.fr.web.core.ReportBackgroundDimension;
import com.fr.web.core.Service;
import com.fr.web.core.SessionIDInfor;
import com.fr.web.core.WebUtils;
import com.fr.web.core.chwriter.EditCellWriter;
import java.awt.Dimension;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EditService
  implements Service
{
  private static EditService SC = new EditService();
  private static boolean supportEdit = true;

  public static EditService getInstance()
  {
    return SC;
  }

  public boolean accept(String paramString)
  {
    return ((supportEdit) && (paramString.startsWith("edit_")));
  }

  public void process(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, String paramString1, String paramString2)
    throws Exception
  {
    SessionIDInfor localSessionIDInfor = SessionDealWith.getSessionIDInfor(paramString2);
    if (localSessionIDInfor == null)
    {
      ErrorHandlerHelper.getErrorHandler().error(paramHttpServletRequest, paramHttpServletResponse, "SessionID: \"" + paramString2 + "\" time out.");
      return;
    }
    if ("edit_init".equals(paramString1))
      initEditPage(localSessionIDInfor, paramHttpServletRequest, paramHttpServletResponse);
    else if ("edit_content".equals(paramString1))
      getReportContent(localSessionIDInfor, paramHttpServletRequest, paramHttpServletResponse);
    else if ("edit_savedata".equals(paramString1))
      saveData(localSessionIDInfor, paramHttpServletRequest, paramHttpServletResponse);
    else if ("edit_savereport".equals(paramString1))
      saveReport(localSessionIDInfor, paramHttpServletRequest, paramHttpServletResponse);
    else if ("edit_calcualte".equals(paramString1))
      calculate(localSessionIDInfor, paramHttpServletRequest, paramHttpServletResponse);
  }

  private static void getReportContent(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    int i = Integer.parseInt(WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "reportIndex"));
    Report localReport = paramSessionIDInfor.getReport2Show(i);
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    writeReportPane(localPrintWriter, localReport, i, new Repository(paramHttpServletRequest, paramSessionIDInfor));
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private static void writeReportPane(PrintWriter paramPrintWriter, Report paramReport, int paramInt, Repository paramRepository)
  {
    Tag localTag1 = new Tag("div");
    localTag1.cls("sheet-container");
    if (paramRepository.getBrowser().shouldSetOverflowAsHiddenOnSheetContainer())
      localTag1.css("overflow", "hidden");
    HTMLWriter localHTMLWriter = HTMLWriter.getInstance();
    ColumnRow localColumnRow = (paramReport.getReportPageAttr() == null) ? null : paramReport.getReportPageAttr().getFreezeColumnRow();
    if (localColumnRow != null)
    {
      localHTMLWriter.writeFrozenContent(localTag1, paramReport, localColumnRow, paramInt, new EditCellWriter(paramRepository, paramInt), paramRepository);
    }
    else
    {
      Tag localTag2 = localHTMLWriter.writeJSReport(paramReport, paramInt, new EditCellWriter(paramRepository, paramInt), paramRepository);
      DynamicValueList localDynamicValueList1 = ReportHelper.getColumnWidthList(paramReport);
      DynamicValueList localDynamicValueList2 = ReportHelper.getRowHeightList(paramReport);
      int i = Math.max(localDynamicValueList1.getRangeValueFromZero(paramReport.getColumnCount()), 1);
      int j = Math.max(localDynamicValueList2.getRangeValueFromZero(paramReport.getRowCount()), 1);
      Tag localTag3 = new Tag("div").cls("fr-edit-sheetcontent-container");
      HTMLWriterUtils.writeBackground(localTag3, ReportUtils.getReportSettings(paramReport).getBackground(), new ReportBackgroundDimension(i + 5, j + 5), false, paramRepository, false);
      localTag3.sub(localTag2);
      localTag1.sub(localTag3);
      Iterator localIterator = paramReport.floatIterator();
      while (localIterator.hasNext())
      {
        FloatElement localFloatElement = (FloatElement)localIterator.next();
        Object localObject = null;
        NameJavaScriptGroup localNameJavaScriptGroup = localFloatElement.getNameHyperlinkGroup();
        if ((localNameJavaScriptGroup != null) && (localNameJavaScriptGroup.size() > 0))
        {
          localObject = new Tag("span");
          String str = "{}";
          try
          {
            str = HTMLWriterUtils.writeJSLinkContent(localNameJavaScriptGroup, paramRepository);
          }
          catch (JSONException localJSONException)
          {
            FRContext.getLogger().log(Level.WARNING, localJSONException.getMessage(), localJSONException);
          }
          ((Tag)localObject).attr("onclick", "FR.doHyperlink(event ||window.event," + str + ")");
          ((Tag)localObject).css("cursor", "pointer");
        }
        int k = localDynamicValueList1.getRangeValueFromZero(localFloatElement.getColumn()) + localFloatElement.getLeftDistance();
        int l = localDynamicValueList2.getRangeValueFromZero(localFloatElement.getRow()) + localFloatElement.getTopDistance();
        int i1 = localFloatElement.getSize().width + 1;
        int i2 = localFloatElement.getSize().height + 1;
        i = Math.max(i, k + i1);
        j = Math.max(j, l + i2);
        Tag localTag4 = new Tag("div");
        if (localObject == null)
          localObject = localTag4;
        else
          ((Tag)localObject).sub(localTag4);
        localTag3.sub((Html)localObject);
        localTag4.css("overflow", "hidden");
        localTag4.css("position", "absolute");
        localTag4.css("left", k + "px");
        localTag4.css("top", l + "px");
        localTag4.css("width", i1 + "px");
        localTag4.css("height", i2 + "px");
        localTag4.sub(localFloatElement.toTag(paramRepository));
      }
      localTag3.css("width", (i + 5) + "px").css("height", (j + 5) + "px");
    }
    localTag1.writeHtml(paramPrintWriter);
  }

  private static void initEditPage(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    Map localMap = WebUtils.context4CommonPaneTpl(paramHttpServletRequest, paramSessionIDInfor);
    Repository localRepository = new Repository(paramHttpServletRequest, paramSessionIDInfor);
    int i = paramSessionIDInfor.getReportCount();
    JSONArray localJSONArray = new JSONArray();
    for (int j = 0; j < i; ++j)
      localJSONArray.put(new JSONObject().put("title", paramSessionIDInfor.getReportName(j)));
    localMap.put("sheets", localJSONArray);
    localMap.put("browserbg", HTMLWriterUtils.jsonBackground(ReportUtils.getBrowserBackgroundFromWorkBook(paramSessionIDInfor.getContextBook()), localRepository));
    try
    {
      TemplateUtils.dealWithTemplate("/com/fr/web/core/edit.html", paramHttpServletResponse, localMap);
    }
    catch (IOException localIOException)
    {
      FRContext.getLogger().log(Level.WARNING, localIOException.getMessage(), localIOException);
    }
  }

  private static void saveReport(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    int i = 0;
    try
    {
      saveData(paramSessionIDInfor, paramHttpServletRequest, paramHttpServletResponse);
      ResultWorkBook localResultWorkBook = paramSessionIDInfor.getWorkBook2Show();
      String str = FRContext.getConfigManager().getResultSaverClassName();
      Object localObject1 = null;
      if (StringUtils.isBlank(str))
      {
        localObject1 = DefaultResultSaver.getInstance();
      }
      else
      {
        Object localObject2 = null;
        try
        {
          Class localClass = FRCoreContext.classForName(str);
          localObject2 = localClass.newInstance();
        }
        catch (Exception localException2)
        {
          FRContext.getLogger().log(Level.WARNING, localException2.getMessage(), localException2);
        }
        if (localObject2 instanceof ResultSaver)
          localObject1 = (ResultSaver)localObject2;
      }
      for (int j = 0; j < localResultWorkBook.getReportCount(); ++j)
        localResultWorkBook.getResultReport(j).recalculate(paramSessionIDInfor.getParameterMap4Execute());
      if (localObject1 != null)
      {
        ((ResultSaver)localObject1).save(localResultWorkBook, paramSessionIDInfor.getReportletTitle(), Collections.EMPTY_MAP);
        i = 1;
      }
    }
    catch (Exception localException1)
    {
      i = 0;
      throw localException1;
    }
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    localPrintWriter.print((i != 0) ? "success" : "failure");
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  private static void saveData(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    RWorkBook localRWorkBook;
    ResultWorkBook localResultWorkBook;
    int j;
    String str = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "editReportXML");
    if ((str != null) && (str.length() > 0))
    {
      ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
      localRWorkBook = new TemplateImporter().generateResult(localByteArrayInputStream);
      localResultWorkBook = paramSessionIDInfor.getWorkBook2Show();
      int i = localRWorkBook.getReportCount();
      for (j = 0; j < i; ++j)
      {
        Report localReport1 = localRWorkBook.getReport(j);
        Report localReport2 = localResultWorkBook.getReport(Integer.valueOf(localRWorkBook.getReportName(j)).intValue());
        Iterator localIterator = localReport1.cellIterator();
        while (localIterator.hasNext())
        {
          EditResultWorkSheet.EditCellELement localEditCellELement = (EditResultWorkSheet.EditCellELement)localIterator.next();
          CellElement localCellElement = localReport2.getCellElement(localEditCellELement.getColumn(), localEditCellELement.getRow());
          localEditCellELement.checkDirtyValueAndStyle(localCellElement, localReport2);
        }
      }
    }
  }

  private static void calculate(SessionIDInfor paramSessionIDInfor, HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws Exception
  {
    Object localObject;
    String str1 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "ptype");
    String str2 = WebUtils.getHTTPRequestParameter(paramHttpServletRequest, "pcontent");
    PrintWriter localPrintWriter = WebUtils.createPrintWriter(paramHttpServletResponse);
    Object[] arrayOfObject = new Object[1];
    if ("parameter".equals(str1))
    {
      localObject = paramSessionIDInfor.getParameterValue(str2);
      arrayOfObject[0] = CodeUtils.object2JSONable(localObject);
    }
    else if ("expression".equals(str1))
    {
      localObject = Calculator.createCalculator();
      ((Calculator)localObject).setCurrentTableDataSource(paramSessionIDInfor.getContextBook());
      arrayOfObject[0] = CodeUtils.object2JSONable(((Calculator)localObject).eval(str2));
    }
    new JSONArray(arrayOfObject).write(localPrintWriter);
    localPrintWriter.flush();
    localPrintWriter.close();
  }

  static
  {
    byte[] arrayOfByte = FRCoreContext.getBytes();
    ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    try
    {
      RSADecode.decode(arrayOfByte, localByteArrayOutputStream);
    }
    catch (Exception localException1)
    {
    }
    try
    {
      JSONObject localJSONObject = new JSONObject(new String(localByteArrayOutputStream.toByteArray(), "UTF-8"));
      supportEdit = (localJSONObject.getLong("deadline") > Calendar.getInstance().getTimeInMillis()) && (localJSONObject.has("version")) && (ComparatorUtils.equals(Consts.VERSION, localJSONObject.getString("version"))) && (((localJSONObject.getLong("deadline") - Calendar.getInstance().getTimeInMillis() < 3153600000L) || ((localJSONObject.has("macaddress")) && (BaseCoreUtils.getMacAddresses().contains(localJSONObject.getString("macaddress")))))) && (VT4FR.ONLINE_EDIT.support());
    }
    catch (Exception localException2)
    {
    }
  }
}